import React, {Component, Fragment} from "react";
// antd
import { Modal, message, Tree } from "antd";
// http
import http from '../../../utils/request';


class UserMenuModal extends Component {
    constructor(props) {
        super(props)
        this.state = {
            menuUserKeyList: false,
            menuUserId: '',
            menuVisible: false,
            menuData: ['null'],
            menuSelectList: []
        }
    }

    /** 子组件调用父组件必须 */
    componentDidMount(){
        this.props.onRef(this);
    }

    /** 弹窗 */
    visableModal = (params) => {
        this.setState({
            menuVisible: params.status,           
            menuUserId: params.user_id
        })
        // 获取全部菜单列表与用户当前的菜单列表
        http.get('/menu/user',{params: {'user_id': params.user_id} }).then(response=>{
            console.log('response: ', response.data.data.user_menu_key_list)
            this.setState({
                menuData: response.data.data.menu_list,
                menuUserKeyList: response.data.data.user_menu_key_list,
            })
        }).catch()
    }

    /** 关闭弹窗 */
    handleCancel = () => {
        this.setState({
            menuVisible: false,
            menuUserKeyList: false,
        })
    }

    /** 用户选择菜单 */
    menuCheck = (checkedKeys) => {
        this.setState({
            menuSelectList: checkedKeys,
        })
    };

    /** 修改用户菜单 */
    menuHandSubmit = () => {
        const requestData = {
            'user_id': this.state.menuUserId,
            'menu_select_list': this.state.menuSelectList,
        }
        http.post('/menu/user', requestData).then(response=>{
            message.info('用户菜单修改成功')
            this.setState({
                menuVisible: false,
                menuUserKeyList: false,
            })
        }).catch()
    }

    render() {
        const { menuUserKeyList, menuData } = this.state
        return (
            <Fragment>
                { menuData.length && menuUserKeyList.length && (
                <Modal
                    title="用户菜单"
                    visible={this.state.menuVisible}
                    onOk={this.menuHandSubmit}
                    onCancel={this.handleCancel}
                    okText="确认"
                    cancelText="取消"
                >
                    <Tree
                        checkable
                        defaultExpandedKeys={menuUserKeyList}   // 默认展开数据
                        defaultCheckedKeys={menuUserKeyList}    // 默认选中菜单
                        onCheck={this.menuCheck}
                        treeData={menuData}                     // 数据源
                    />
                </Modal>)}
            </Fragment>
        )
    }
}

export default UserMenuModal;
